<!--
 * @Description: 使用 https://www.swiper.com.cn/demo/index.html#virtual-slides
 * API: https://www.swiper.com.cn/api/virtual/374.html
 * vue 使用: https://swiperjs.com/vue
 * @Version: 0.0.1
 * @Autor: zhj1214
 * @Date: 2024-02-07 10:07:39
 * @LastEditors: zhj1214
 * @LastEditTime: 2024-09-06 22:26:40
-->
<template>
  <div class="verticalSwipe">
    <!-- 标题 -->
    <div class="verticalSwipe-title items-center">
      <div class="verticalSwipe-title-value">
        {{ $t("lotteryMoney.dqcyrs") }}
        <span style="margin-right: 2px">{{ peoples }}</span>
      </div>
    </div>
    <!-- 轮播 -->
    <template v-if="slides.length > 0">
      <!-- <transition-group name="list" tag="ul"> -->
      <div
        class="item-animation"
        v-for="(item, index) in slides"
        :key="`${item && item.sid}${item && item.id}${item && item.drawTime}`"
      >
        <div
          v-if="index < 5"
          class="item-animation item-bg-flex"
          :class="{
            'item-bg': index % 2 == 0,
          }"
        >
          <div class="item items-center">
            <div class="items-center">
              <ImgNuxt
                class="item-avatar"
                isHttp
                :placeholder="file.avatarDefault"
                :src="item.avatar || file.avatarDefault"
              />
              <div class="item-nickname">{{ item.nickname || "--" }}</div>
            </div>
            <!-- <div class="item-text">{{ $t("lotteryMoney.xzcg") }}</div> -->
            <div class="item-time" style="text-align: center">
              {{ useDateFormat(Number(item.drawTime), "HH:mm:ss").value }}
            </div>
            <div class="item-team" style="text-align: right">
              {{ item.teamName }}
            </div>

            <!-- <div class="item-btn">
                {{ $t("lotteryMoney.slz") }}
              </div> -->
          </div>
        </div>
      </div>
      <!-- </transition-group> -->
    </template>
    <div v-else class="verticalSwipe-notdata items-center">
      <img
        class="verticalSwipe-notdata-img"
        src="/image/lotterymoney/zwsj-icon.svg"
      />
      <div class="verticalSwipe-notdata-text">
        {{ $t("lotteryMoney.zwsj") }}
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="verticalSwipe">
import { onMounted } from "vue";
import { getOssFileUrl, navigateI18nTo } from "@/utils";
import { useEventBus, useDateFormat } from "@vueuse/core";
import { getRecentRecord } from "@/api/lottery";
import { useLotteryMoneyStore } from "~~/store/modules/lottery-money";

const props = withDefaults(
  defineProps<{
    centerindex?: number;
    peoples: string | number;
    activitytStatus: number;
    serverTime: number;
    sessionId: string | number;
    lotteryPoolAmount: string | number;
    sessionUserCount: string | number;
    sessionTotalDrawCount: string | number;
  }>(),
  {
    centerindex: 0,
    peoples: 0,
    activitytStatus: 1, //   1 未开始  2 进行中  3 已结束
    serverTime: 0, // 服务器时间
    sessionId: "",
  }
);

const emit = defineEmits(["initDone", "update:centerindex", "change"]);

const lotteryMoneyStore = useLotteryMoneyStore();

const { t } = useI18n();
// 资源
const file = getOssFileUrl({
  avatarDefault: "/image/avatar-default.png",
});
// 列表数据
const slides = ref([]);

// 活动状态变更,数据重置
watch(
  () => props.activitytStatus,
  (newVal, oldVal) => {
    if (newVal != 2) {
      slides.value = [];
      recordlast.value = null;
    }
  }
);
// 获取最新-服务器时间
const serverTime = computed(() => {
  if (serverTimeChange.value > 0) {
    return serverTimeChange.value;
  } else if (props.serverTime > 0) {
    return props.serverTime;
  } else {
    return Date.now();
  }
});

// socket 消息推送
const betSocket = useEventBus("lotteryMoney-socket-bdcLotteryBetting");
let betSocketOn = betSocket.on((val: any) => {
  // 有人下注了: 添加到数组第一位
  if (val.betUser) {
    if (val.betUser.teamConfigId == 1) {
      val.betUser.teamName = t("lotteryMoney.redTeam");
    } else if (val.betUser.teamConfigId == 2) {
      val.betUser.teamName = t("lotteryMoney.yellowTeam");
    } else if (val.betUser.teamConfigId == 3) {
      val.betUser.teamName = t("lotteryMoney.blueTeam");
    }

    recordlast.value = val.betUser;
    slides.value.unshift(val.betUser);
    slides.value = slides.value.sort((a: any, b: any) => {
      return Number(b.drawTime) - Number(a.drawTime);
    });
    if (slides.value.length > 50) {
      slides.value = slides.value.slice(0, 10);
    }
  }
});
// 定时器-通知
const serverTimeChange = ref(0);
let minShowNums = 5; // 最少展示几条就上滑
const moneyInterval = useEventBus("lottery-money-interval-emit");
let moneyIntervalEmit: any = null;

// 下注成功通知,刷新数据
const betSuccess = useEventBus("lottery-money-bet-Success");
betSuccess.on(() => {
  if (lotteryMoneyStore.$state.drawStage == 1) getRecentRecordRequest();
});
/**
 * @description: 获取下注列表: 接口返回的数据,最新的在数组第一条的位置
 * 1. 接口获取的数据,按照最近 5 分钟时间过滤出最近的 50 条,不够则获取最近的 5 条
 */
const mock = ref([]);
const recordlast = ref(null); // 滚动列表最后一条记录

const getRecentRecordRequest = () => {
  // 是否需要轮询
  if (!lotteryMoneyStore.isNeedPolling) return;
  getRecentRecord({ limit: 10 }).then((res) => {
    if (res && props.activitytStatus == 2) {
      if (!lotteryMoneyStore.$state.isDoneBetList) {
        lotteryMoneyStore.$patch((state) => {
          state.isDoneBetList = state.isUseSocketing && true;
        });
      }
      if (res.recentDrawRecordList && res.recentDrawRecordList.length > 0) {
        slides.value = res.recentDrawRecordList;
      }

      // if (res.recentDrawRecordList && res.recentDrawRecordList.length > 0) {
      //   // zhjdebugger
      //   // res.recentDrawRecordList = res.recentDrawRecordList.splice(0, 10);
      //   // console.log('--serverTime.value--',serverTime.value);

      //   // 过滤出最近 5 分钟数据
      //   let source: any = [];
      //   res.recentDrawRecordList.forEach((element: any) => {
      //     if (
      //       (Number(element.drawTime) || 0) >
      //       Number(serverTime.value) - 5 * 60 * 1000
      //     ) {
      //       source.push(element);
      //     }
      //   });

      //   // 第一次请求
      //   if (!recordlast.value) {
      //     // 第一次 不足 5 条
      //     if (source.length < minShowNums) {
      //       source = res.recentDrawRecordList.splice(0, minShowNums);
      //     }
      //     // 重排一次
      //     source = source.sort((a: any, b: any) => {
      //       return Number(b.drawTime) - Number(a.drawTime);
      //     });
      //     // 保存时间最大的一条
      //     recordlast.value = source[0];
      //     // 赋值数据源
      //     if (source.length >= minShowNums) {
      //       slides.value = source.splice(
      //         source.length - minShowNums,
      //         source.length
      //       );
      //       // slides.value = source.splice(0, 5);
      //       // 剩余的
      //       mock.value = source;
      //     } else {
      //       slides.value = source;
      //       mock.value = [];
      //     }
      //   }
      //   // 后续的请求
      //   else {
      //     // 1. 跟最后一条比较时间,大的,追加
      //     let addArr: any = [];
      //     source.forEach((element: any) => {
      //       if (Number(element.drawTime) > Number(recordlast.value.drawTime)) {
      //         // console.log("增量数据++", element);
      //         addArr.push(element);
      //       }
      //     });
      //     // 2. 按照时间排序,从小到大
      //     if (addArr && addArr.length > 0) {
      //       // 合并数据
      //       addArr = mock.value.concat(addArr);
      //       // 排序
      //       mock.value = addArr.sort((a: any, b: any) => {
      //         return Number(b.drawTime) - Number(a.drawTime);
      //       });
      //       // 赋值,最后一条记录
      //       recordlast.value = mock.value[0];
      //     }
      //   }
      // }
    }
  });
};

// 页面加载以后: 优化加载速度,带优化
watch(
  () => props.activitytStatus,
  (newVal, oldVal) => {
    if (newVal == 2) {
      if (lotteryMoneyStore.$state.drawStage == 1) getRecentRecordRequest();
    }
  }
);
onMounted(() => {
  if (!moneyIntervalEmit) {
    // moneyIntervalEmit = moneyInterval.on((val: any) => {
    //   // console.log(mock.value.length, "vertical-swipe-定时器", slides.value.length);
    //   serverTimeChange.value = val;
    //   if (props.activitytStatus != 2) return;
    //   // 1.1 每隔 3 秒 更新一次
    //   // if (val % 15000 > 14000 || val % 15000 == 0) {
    //   //   // 是否需要请求新数据
    //   //   if (mock.value.length <= 2) {
    //   //     getRecentRecordRequest();
    //   //   }
    //   // }
    //   // 没间隔 1 秒: 是否需要滚动
    //   const max: any = mock.value.pop(); // 去数组0 的元素
    //   if (max) {
    //     slides.value.unshift(max);
    //     slides.value = slides.value.sort((a: any, b: any) => {
    //       return Number(b.drawTime) - Number(a.drawTime);
    //     });
    //   }
    // });
  }

  if (props.activitytStatus == 2) {
    getRecentRecordRequest();
  }
});
onBeforeUnmount(() => {
  moneyIntervalEmit && moneyIntervalEmit();
  betSocketOn && betSocketOn();
});
</script>
<style lang="scss" scoped>
.verticalSwipe {
  width: 100%;
  padding-bottom: 5 * 2px;
  &-title {
    position: relative;
    justify-content: center;
    &-value {
      padding: 1 * 2px 8 * 2px;
      padding: 4 * 2px 12 * 2px;
      border-top-left-radius: 4 * 2px;
      border-top-right-radius: 4 * 2px;
      font-size: 12 * 2px;
      color: #fff;
      background: linear-gradient(90deg, #007bff 0.07%, #00b2ff 99.93%);
    }
  }
  &-notdata {
    min-height: 120 * 2px;
    flex-direction: column;
    justify-content: center;
    &-text {
      text-align: center;
      font-size: 14 * 2px;
      color: #999da7;
    }
    &-img {
      margin-bottom: 8 * 2px;
      width: 50 * 2px;
    }
  }
  &-record {
    position: absolute;
    top: 0;
    right: 8 * 2px;
    padding: 6.5 * 2px 0;
    color: #2a91ff;
    font-size: 10 * 2px;
    font-weight: 600;
  }
}
.item {
  position: relative;
  justify-content: space-between;
  width: 100%;
  padding: 0 10 * 2px;

  &-bg {
    background: linear-gradient(
      90deg,
      rgba(235, 244, 255, 0) 0%,
      #ebf4ff 50.17%,
      rgba(235, 244, 255, 0) 100%
    );
    &-flex {
      display: flex !important;
      align-items: center;
      // margin: 8 * 2px 0;
      padding: 5.2 * 2px 0;
    }
  }
  &-avatar {
    width: 18 * 2px;
    height: 18 * 2px;
    border-radius: 100px;
    overflow: hidden;
    margin-right: 4 * 2px;
  }
  &-nickname {
    @include multi-line-omit(1);
    min-width: 82 * 2px;
    max-width: 82 * 2px;
    color: #002853;
    font-size: 12 * 2px;
    font-weight: 400;
    margin-right: 11 * 2px;
  }
  &-team {
    min-width: 64 * 2px;
    color: #002853;
    font-size: 12 * 2px;
    font-weight: 400;
    margin-right: 11 * 2px;
  }
  &-time {
    min-width: 64 * 2px;
    color: #002853;
    font-size: 12 * 2px;
    font-weight: 400;
    margin-right: 11 * 2px;
  }

  &-btn {
    color: #007bff;
    font-size: 12 * 2px;
    font-weight: 400;
  }
}
.item-animation {
  transition: all 0.5s;
}
.list-enter-active,
.list-leave-active {
  transition: all 0.5s;
}

.list-enter, .list-leave-to /* .list-leave-active in <2.1.8 */ {
  opacity: 0;
  transform: translateY(-30px);
}
</style>
